package com.xishu.controller;

import com.alibaba.fastjson.JSON;
import com.stripe.Stripe;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.Event;
import com.stripe.model.PaymentIntent;
import com.stripe.model.terminal.ConnectionToken;
import com.stripe.model.terminal.Reader;
import com.stripe.net.Webhook;
import com.stripe.param.PaymentIntentCreateParams;
import com.stripe.param.terminal.ConnectionTokenCreateParams;
import com.xishu.annotation.valid.Admin;
import com.xishu.annotation.valid.MethodValidator;
import com.xishu.bo.StripeRequest;
import com.xishu.bo.StripeResponse;
import com.xishu.config.Config;
import com.xishu.entity.Company;
import com.xishu.entity.customer.VipRenewEmailTemplate;
import com.xishu.entity.order.Order;
import com.xishu.service.order.callback.OrderCallBackService;
import com.xishu.entity.payment.PaymentCheck;
import com.xishu.entity.shop.PayType;
import com.xishu.entity.shop.Shop;
import com.xishu.entity.shop.StripeLocation;
import com.xishu.entity.shop.StripeReader;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.*;
import com.xishu.service.order.base.OrderService;
import com.xishu.util.AES;
import com.xishu.util.ServletUtil;
import com.xishu.util.Tools;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.xishu.config.Constant.*;
import static com.xishu.response.ResponseStatus.*;

@CrossOrigin
@RestController
public class StripeController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(StripeController.class);

    private CommonService commonService = CommonService.getInstance();
    private OrderService orderService = OrderService.getInstance();
    private StripeService stripeService = StripeService.getInstance();
    private LockService localLockService = LockService.getInstance();

    /**
     * @param stripeRequest
     * @return
     */
    @PostMapping(value = ("/stripe/pay/secret"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(mustLogin = false)
    public ResponseData paySecret(@RequestBody StripeRequest stripeRequest) throws Exception {
        Long orderId = stripeRequest.getOrderId();
        Long shopId = stripeRequest.getShopId();
        Long companyId = stripeRequest.getCompanyId();
        VerifyUtil.verify(() -> isNotEmpty(orderId), ORDER_CANCEL_CONFIG_PAY_TYPE);
        VerifyUtil.verify(() -> isNotEmpty(shopId) || isNotEmpty(companyId), ORDER_CANCEL_CONFIG_PAY_TYPE);

        //有对应的last4，查询生成paymentIntent
        synchronized (GlobalService.GLOBAL_LOCK) {
            PaymentIntent paymentIntent = null;
            if (companyId != null) {
                logger.info("will get payment intent from company");
                paymentIntent = stripeService.createPaymentIntent_companyId(companyId, orderId);
            } else {
                paymentIntent = stripeService.createPaymentIntent(shopId, orderId);
            }

            logger.info("secret is {}", paymentIntent.getClientSecret());
            StripeResponse stripeResponse = new StripeResponse();
            stripeResponse.setSecretKey(paymentIntent.getClientSecret());
            stripeResponse.setPayMethodId(paymentIntent.getPaymentMethod());
            return commonService.createResponse(stripeResponse);
        }
    }

    /**
     * 异步通知
     *
     * @return
     */
    @PostMapping(value = ("/ssl/stripe/webhook"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(mustLogin = false)
    public String webhook(@RequestBody String payload) {
        logger.info("come in webhook");
        String sigHeader = ServletUtil.getRequest().getHeader("Stripe-Signature");
        logger.info("sig Header is {}", sigHeader);
        logger.info("pay load is {}", payload);

        try {
            Long shopId = getStripeShopId(payload);
            Shop shop = null;
            String webHookSk = null;

            if (shopId != null) {
                shop = ShopService.getInstance().findShopById(shopId);
                if (shop == null) {
                    logger.info("can not find the shop");
                    return "error";
                }

                webHookSk = AES.decrypt(shop.getStripeWebHookSk());
            } else {
                Long companyId = getStripeCompanyId(payload);
                Company company = CompanyService.getInstance().findCompanyById(companyId);
                if (company == null) {
                    logger.info("company is null");
                    return "error";
                }

                VipRenewEmailTemplate vipRenewEmailTemplate = CompanyService.getInstance().findVipRenewEmailTemplate(companyId);
                logger.info("find the vip template {}", vipRenewEmailTemplate.toString());
                webHookSk = AES.decrypt(vipRenewEmailTemplate.getStripeWebHookSk());
            }

            if (Config.getInstance().isWindows()) {
                dealOkOrder(payload);
                return "OK";
            }

            logger.info("web hook sk is {}", webHookSk);
            Event event = Webhook.constructEvent(payload, sigHeader, webHookSk);
            logger.info("parse success");

            String eventType = event.getType();
            if (equals(eventType, "payment_intent.succeeded")) {
                logger.info("payment intent");
                dealOkOrder(payload);
                return "OK";
            } else if (equals(eventType, "charge.succeeded")) {
                logger.info("charge succeeded");
                dealOkOrder(payload);
                return "OK";
            } else {
                Thread.sleep(30 * 1000);
                logger.info("event type {} not deal", eventType);
                return "error";
            }

        } catch (SignatureVerificationException e) {
            logger.error("e", e);
            return "error";
        } catch (Exception e) {
            logger.error("e", e);
            return "error";
        }
    }

    /**
     * stripe里面的orderId 是由shopId:orderId组成的
     *
     * @param payload
     * @return
     */
    private Long getStripeOrderId(String payload) {
        JSONObject json = JSONObject.fromObject(payload);
        JSONObject medatadaJson = json.getJSONObject("data").getJSONObject("object").getJSONObject("metadata");
        logger.info("metadata is {}", medatadaJson.toString());

        return medatadaJson.getLong("orderId");
    }

    /**
     * 获取分店ID
     *
     * @param payload
     * @return
     */
    private Long getStripeShopId(String payload) {
        try {
            JSONObject json = JSONObject.fromObject(payload);
            JSONObject medatadaJson = json.getJSONObject("data").getJSONObject("object").getJSONObject("metadata");
            logger.info("metadata is {}", medatadaJson.toString());

            return medatadaJson.getLong("shopId");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取餐桌
     *
     * @param payload
     * @return
     */
    private Long getStripeCompanyId(String payload) {
        try {
            JSONObject json = JSONObject.fromObject(payload);
            JSONObject medatadaJson = json.getJSONObject("data").getJSONObject("object").getJSONObject("metadata");
            logger.info("metadata is {}", medatadaJson.toString());

            return medatadaJson.getLong("companyId");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 是否是终端刷卡回调
     *
     * @param payload
     * @return
     */
    private boolean getTerminal(String payload) {
        try {
            JSONObject json = JSONObject.fromObject(payload);
            JSONObject medatadaJson = json.getJSONObject("data").getJSONObject("object").getJSONObject("metadata");
            logger.info("metadata is {}", medatadaJson.toString());

            String terminal = medatadaJson.getString(STRIPE_METADATA_TERMINAL);
            return terminal != null;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 处理支付成功的订单
     *
     * @param payload
     * @throws Exception
     */
    private void dealOkOrder(String payload) throws Exception {
        logger.info("in success");
        Long orderId = getStripeOrderId(payload);
        Long shopId = getStripeShopId(payload);
        Long companyId = getStripeCompanyId(payload);

        String paymentId = StripeService.getInstance().getPaymentId(payload);
        Optional<PaymentIntent> paymentIntentOptional = stripeService.retrievePaymentIntent(paymentId, shopId);
        String bank = stripeService.getBrand(paymentIntentOptional);

        boolean terminal = getTerminal(payload);

        if (terminal) {
            ThreadContext.put(THREAD_LOCAL_VARIABLE_STRIPE_TERMINAL_PAY, "true");
        }

        Long printId = stripeService.getPrintId(paymentIntentOptional);
        //持卡人名称
        String cardHolderName = stripeService.getCardHolderName(paymentIntentOptional);
        ThreadContext.put(THREAD_LOCAL_VARIABLE_CARD_HOLDER_NAME, cardHolderName);
        //后4位
        String last4 = stripeService.getLast4(paymentIntentOptional);
        ThreadContext.put(THREAD_LOCAL_VARIABLE_CARD_LAST4, last4);

        try {
            orderCallback(orderId, shopId, companyId, paymentId, bank, printId);
        } finally {
            ThreadContext.remove(THREAD_LOCAL_VARIABLE_STRIPE_TERMINAL_PAY);
        }

    }

    private void orderCallback(Long orderId, Long shopId, Long companyId, String paymentId, String bank, Long printId) throws Exception {
        try {
            String lockKey = null;
            if (companyId != null) {
                lockKey = OrderService.getInstance().getLockKey(companyId, orderId);
            } else {
                lockKey = OrderService.getInstance().getLockKey(shopId, orderId);
            }

            Object lock = localLockService.getLock(lockKey);
            synchronized (lock) {
                Order order = null;
                if (companyId != null) {
                    order = OrderService.getInstance().findOrder(orderId);
                } else {
                    order = OrderService.getInstance().findOrderCanFlagDelete(shopId, orderId);
                }

                //添加打印ID
                order.setPrinterId(printId);

                //正在支付的订单，修改订单状态
                if (getBoolean(order.getPayed())) {
                    logger.info("order payed");
                    return;
                }

                //先把Apple Pay和Google Pay保存下来
                if (getInt(order.getPayType()) == ORDER_PAY_TYPE_APPLE) {
                    order.setSubStripePayType(APPLE_PAY);
                } else if (getInt(order.getPayType()) == ORDER_PAY_TYPE_GOOGLE) {
                    order.setSubStripePayType(GOOGLE_PAY);
                }

                //添加stripe支付
                order.setPayType(ORDER_PAY_TYPE_STRIPE);

                //处理银行卡
                if (isEmpty(order.getSubStripePayType())) {
                    logger.info("bank is {}", bank);
                    order.setSubStripePayType(bank);
                }

                order.setPayedWith3rd(true);
                order.setStripePaymentId(paymentId);

                //已支付，回调
                if (getBoolean(order.getVipOrder())) {
                    OrderCallBackService.getInstance().dealVipOrder(order);
                } else {
                    OrderCallBackService.getInstance().orderCallback(order);
                }
            }
        } finally {
            //移除刷卡人信息
            ThreadContext.remove(THREAD_LOCAL_VARIABLE_CARD_HOLDER_NAME);
        }
    }

    /**
     * 从stripe里面获取到银行卡
     *
     * @param payLoad
     * @return
     */
    public String getBankTypeInPayLoad(String payLoad) {
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(payLoad);
        if (!jsonObject.containsKey("data")) {
            logger.info("data error");
            return "";
        }

        com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("data");
        if (!data.containsKey("object")) {
            logger.info("object error");
            return "";
        }

        com.alibaba.fastjson.JSONObject object = data.getJSONObject("object");

        if (!object.containsKey("payment_method_details")) {
            logger.info("payment_method_details error");
            return "";
        }

        com.alibaba.fastjson.JSONObject payment_method_details = object.getJSONObject("payment_method_details");
        if (!payment_method_details.containsKey("card")) {
            logger.info("card error");
            return "";
        }

        com.alibaba.fastjson.JSONObject card = payment_method_details.getJSONObject("card");
        if (!card.containsKey("brand")) {
            logger.info("brand error");
            return "";
        }

        return card.getString("brand");
    }

    @PostMapping(value = ("/stripe/address"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true, checkShopId = true)
    @ApiOperation(value = "创建位置")
    public ResponseData createLocation(@RequestBody StripeLocation stripeLocation) throws Exception {
        stripeLocation.setCountry("US");
        Long shopId = stripeLocation.getShopId();
        VerifyUtil.verify(() -> shopId != null);
        //所有数据均需要填写
        VerifyUtil.isEmpty(stripeLocation.getCity(), stripeLocation.getState(), stripeLocation.getLine1(), stripeLocation.getCountry(), stripeLocation.getZipCode());
        Shop shop = ShopService.getInstance().findShopById(shopId);
        stripeLocation.setCompanyId(shop.getCompanyId());
        stripeService.createLocation(stripeLocation);

        //查询支付方式，如果不存在stripe的支付方式，则创建
        List<PayType> payTypeList = PayTypeService.getInstance().findPayTypeListCache(shopId);

        if (!payTypeList.stream().filter(p -> p.getType() == ORDER_PAY_TYPE_STRIPE).findAny().isPresent()) {
            PayTypeService.getInstance().createDefaultPayType(shopId, shop, "Stripe", "Stripe", ORDER_PAY_TYPE_STRIPE, "us_stripe.png", true);
            //重新查询
            PayTypeService.getInstance().flushPayTypeListCash(shopId);
        }

        return commonService.createResponse(stripeLocation);
    }

    @PutMapping(value = ("/stripe/address/modify"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    @ApiOperation(value = "修改位置")
    public ResponseData updateLocation(@RequestBody StripeLocation stripeLocation) throws Exception {
        ResponseData responseData = commonService.updateObject(stripeLocation);
        StripeLocation stripeLocationInDb = commonService.findEntity(stripeLocation.getId(), StripeLocation.class);

        //如果更新了名称，那么同步修改刷卡机里面的名称
        if (isNotEmpty(stripeLocation.getDisplayName())) {
            List<StripeReader> allReader = stripeService.findAllReader(stripeLocationInDb.getShopId(), stripeLocationInDb.getId());
            allReader.forEach(reader -> {
                reader.setLocationName(stripeLocation.getDisplayName());
                try {
                    commonService.save(reader);
                } catch (Exception e) {
                    logger.error("e", e);
                }
            });
        }

        stripeService.updateLocation(stripeLocationInDb);
        return responseData;
    }

    @PutMapping(value = ("/stripe/address"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "读取位置")
    public ResponseData readLocation(@RequestBody StripeLocation stripeLocation) throws Exception {
        return commonService.searchResponse(stripeLocation);
    }

    @DeleteMapping(value = ("/stripe/address"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    @ApiOperation(value = "删除位置")
    public ResponseData deleteLocation(@RequestBody StripeLocation stripeLocation) throws Exception {
        StripeLocation stripeLocationInDb = commonService.findEntity(stripeLocation.getId(), StripeLocation.class);
        //判断有没有刷卡机，如果有刷卡机则不能够删除
        List<StripeReader> allReader = stripeService.findAllReader(stripeLocationInDb.getShopId(), stripeLocationInDb.getId());
        VerifyUtil.verify(() -> isEmpty(allReader), READER_EXIST_UNDER_LOCATION);
        ResponseData responseData = commonService.delete(stripeLocation);
        stripeService.deleteLocation(stripeLocationInDb);
        return responseData;
    }

    @PostMapping(value = ("/stripe/reader"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true, checkShopId = true)
    @ApiOperation(value = "创建刷卡机")
    public ResponseData createReader(@RequestBody StripeReader stripeReader) throws Exception {
        //参数校验
        Long shopId = stripeReader.getShopId();
        VerifyUtil.verify(() -> shopId != null);

        VerifyUtil.isEmpty(stripeReader.getStripeLocationId(), stripeReader.getRegistrationCode(), stripeReader.getLabel());
        StripeLocation stripeLocation = commonService.findEntity(stripeReader.getStripeLocationId(), StripeLocation.class);

        stripeReader.setLocationName(stripeLocation.getDisplayName());

        //判断标签是否已经存在
        Optional<StripeReader> readerOptional = stripeService.findReader(shopId, stripeReader.getLabel());
        VerifyUtil.verify(() -> !readerOptional.isPresent(), READER_LABEL_EXIST);

        stripeService.createReader(stripeReader);
        return commonService.createResponse(stripeReader);
    }

    @PutMapping(value = ("/stripe/reader/modify"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    @ApiOperation(value = "修改刷卡机，只支持修改标签")
    public ResponseData updateReader(@RequestBody StripeReader stripeReader) throws Exception {
        stripeReader.setRegistrationCode(null);
        stripeReader.setStripeLocationId(null);
        Optional<StripeReader> stripeReaderOptional = stripeService.findReader(stripeReader.getId(), stripeReader.getLabel());
        VerifyUtil.verify(() -> !stripeReaderOptional.isPresent() || equals(stripeReaderOptional.get().getId(), stripeReader.getId()), READER_LABEL_EXIST);
        ResponseData responseData = commonService.updateObject(stripeReader);
        StripeReader stripeReaderInDb = commonService.findEntity(stripeReader.getId(), StripeReader.class);
        stripeService.updateReader(stripeReaderInDb);
        return responseData;
    }

    @PutMapping(value = ("/stripe/reader"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "读刷卡机")
    public ResponseData findReader(@RequestBody StripeReader stripeReader) throws Exception {
        return commonService.searchResponse(stripeReader);
    }

    @DeleteMapping(value = ("/stripe/reader"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "删除刷卡机")
    @MethodValidator(checkShop = true)
    public ResponseData deleteReader(@RequestBody StripeReader stripeReader) throws Exception {
        StripeReader stripeReaderInDb = commonService.findEntity(stripeReader.getId(), StripeReader.class);
        ResponseData responseData = commonService.delete(stripeReader);
        stripeService.deleteReader(stripeReaderInDb);
        return responseData;
    }

    @PostMapping(value = ("/stripe/terminal/connection/token"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "获取连接的token,参数传shopId,以表示获取的是这一个分店的token")
    public ResponseData createConnectionToken(@RequestBody StripeReader stripeReader) throws Exception {
        Long shopId = stripeReader.getShopId();
        VerifyUtil.verify(() -> shopId != null);
        Shop shop = ShopService.getInstance().findShopById(shopId);

        synchronized (GlobalService.GLOBAL_LOCK) {
            logger.info("start connectionToken");
            Stripe.apiKey = AES.decrypt(shop.getStripeSk());
            ConnectionTokenCreateParams params = ConnectionTokenCreateParams.builder().build();
            ConnectionToken connectionToken = ConnectionToken.create(params);
            logger.info("connectionToken success");
            return commonService.createResponse(connectionToken.getSecret());
        }
    }

    @PostMapping(value = ("/stripe/terminal/payment/intent"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "获取订单支付信息,传id(一定是支付订单的ID，需要还涉及到),shopId")
    public ResponseData createTerminalPaymentIntent(@RequestBody Order order) throws Exception {
        Long orderId = order.getId();
        Long shopId = order.getShopId();
        VerifyUtil.verify(() -> orderId != null && shopId != null);
        // For Terminal payments, the 'payment_method_types' parameter must include
        // 'card_present' and the 'capture_method' must be set to 'manual'
        Shop shop = ShopService.getInstance().findShopById(order.getShopId());
        Long printerId = order.getPrinterId();
        String printerIdString = "";

        if (printerId != null) {
            printerIdString = String.valueOf(printerId);
        }

        synchronized (GlobalService.GLOBAL_LOCK) {
            Stripe.apiKey = AES.decrypt(shop.getStripeSk());
            Order orderInDb = OrderService.getInstance().findOrder(shopId, orderId);
            OrderService.getInstance().showPrice(orderInDb, true);

            VerifyUtil.verify(() -> stripeService.checkCost(orderInDb.getUserCost()), NOT_SATISFY_AT_LEAST_COST);

            PaymentIntentCreateParams createParams = PaymentIntentCreateParams.builder()
                    .setCurrency(stripeService.getCurrency(shopId.longValue()))
                    .setAmount(orderInDb.getUserCostLong())
                    .setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.MANUAL)
                    .addPaymentMethodType("card_present")
                    .setDescription(String.format("shop:%s, order perDay no:%s, orderId:%s", shop.getName_en(), order.getOrderNo(), order.getId()))
                    .putMetadata("orderId", String.valueOf(orderId))
                    .putMetadata("shopId", String.valueOf(shop.getId()))
                    .putMetadata("printId", printerIdString)
                    .putMetadata(STRIPE_METADATA_TERMINAL, "true")
                    .build();
            // Create a PaymentIntent with the order amount and currency
            PaymentIntent intent = PaymentIntent.create(createParams);
            logger.info("intent id {}", intent.getId());

            //保存paymentId
            orderInDb.setStripePaymentId(intent.getId());
            commonService.save(orderInDb);

            PaymentCheck paymentCheck = new PaymentCheck(intent.getId(), shopId, orderId);
            commonService.createObject(paymentCheck);

            return commonService.createResponse(intent.getClientSecret());
        }
    }

    @PostMapping(value = ("/stripe/terminal/capture/payment/intent"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "捕获支付信息，传id,以及shopId")
    public ResponseData createCapturePaymentIntent(@RequestBody String str) throws Exception {
        Map<String, Object> map = (Map<String, Object>) com.alibaba.fastjson.JSONObject.parse(str);
        String paymentId = map.get("id").toString();
        Long shopId = Long.valueOf(map.get("shopId").toString());
        VerifyUtil.verify(() -> paymentId != null && shopId != null);
        Shop shop = ShopService.getInstance().findShopById(shopId);

        synchronized (GlobalService.GLOBAL_LOCK) {
            Stripe.apiKey = AES.decrypt(shop.getStripeSk());
            PaymentIntent paymentIntent = PaymentIntent.retrieve(paymentId);
            logger.info("intent is {}", paymentIntent);
            Long orderId = Long.valueOf(paymentIntent.getMetadata().get("orderId"));
            String printIdString = paymentIntent.getMetadata().get("printId");
            Long printId = null;

            if (isNotEmpty(printIdString)) {
                printId = Long.valueOf(printIdString);
            }

            //开始回调处理
            String brand = stripeService.getBrand(paymentIntent);
            //添加终端支付标记
            ThreadContext.put(THREAD_LOCAL_VARIABLE_STRIPE_TERMINAL_PAY, "true");
            //添加持卡人姓名
            String cardHolderName = stripeService.getCardHolderName(paymentIntent);
            ThreadContext.put(THREAD_LOCAL_VARIABLE_CARD_HOLDER_NAME, cardHolderName);
            //添加卡号后4位
            String last4 = stripeService.getLast4(paymentIntent);
            ThreadContext.put(THREAD_LOCAL_VARIABLE_CARD_LAST4, last4);

            orderCallback(orderId, shopId, shop.getCompanyId(), paymentId, brand, printId);
        }

        return ResponseData.emptyResponse();
    }

    @Admin
    @PostMapping(value = ("/stripe/terminal/capture/payment/intent/test"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "捕获支付信息，传id,以及shopId")
    public ResponseData testCapture(@RequestBody String str) throws Exception {
        Map<String, Object> map = (Map<String, Object>) com.alibaba.fastjson.JSONObject.parse(str);
        String paymentId = map.get("id").toString();
        Long shopId = Long.valueOf(map.get("shopId").toString());
        VerifyUtil.verify(() -> paymentId != null && shopId != null);
        Shop shop = ShopService.getInstance().findShopById(shopId);

        synchronized (GlobalService.GLOBAL_LOCK) {
            Stripe.apiKey = AES.decrypt(shop.getStripeSk());
            PaymentIntent intent = PaymentIntent.retrieve(paymentId);
            logger.info("intent is {}", intent);
            Long orderId = Long.valueOf(intent.getMetadata().get("orderId"));
            String printIdString = intent.getMetadata().get("printId");
            Long printId = null;
            Order order = orderService.findOrder(shopId, orderId);
            stripeService.capture(order, shop);
            return commonService.createResponse(order);
        }
    }

    //    @MethodValidator(mustLogin = false)
//    @Admin
//    @PostMapping(value = ("/stripe/intent/test"), produces = ("application/json;charset=UTF-8"))
    public ResponseData retrieve(@RequestBody(required = false) String str) throws Exception {
        Shop shop = ShopService.getInstance().findShopById(31l);
        Stripe.apiKey = AES.decrypt(shop.getStripeSk());
        String id = "tmr_EiTYvg37sooovl";
        Reader reader = Reader.retrieve(id);
        System.out.println("reader = " + reader);

        return ResponseData.emptyResponse();
    }

}
